<?php

namespace app\adminapi\controller;

use think\Cache;
use think\Controller;
use app\common\model\Admin;

class Login extends BaseApi
{
    //获取验证码图片地址
    public function captcha(){
        //验证码标识
        $uniqid = uniqid(mt_rand(100000, 999999));
        //返回数据 验证码图片路径、验证码标识
        $data = [
            'src' => captcha_src($uniqid),
            'uniqid' => $uniqid
        ];
        $this->ok($data);
    }
    public function login(){
        $param = input();
        $validate = $this->validate($param,[
            'username'=>'require',
            'password'=>'require',
            'code'=>'require',
            'uniqid'=>'require',
        ]);
        if ($validate !== true){
            $this->fail($validate);
        }
        //验证验证码
        //校验验证码 手动校验
        //从缓存中根据uniqid获取session_id, 设置session_id, 用于验证码校验
        $session_id = cache('session_id_' . $param['uniqid']);
        if($session_id){
            session_id($session_id);
        }

        if(!captcha_check($param['code'], $param['uniqid']))
        {
            //验证码错误
            //$this->fail('验证码错误', 402);
        }
        $where = [
            'username'=>$param['username'],
            'password'=>encrypt_password($param['password']),
        ];
        $info = Admin::where($where)->find();
        if (!$info){
            $this->fail('用户名或密码错误');
        }
        $data['token'] = \tools\jwt\Token::getToken($info->id);
        $data['user_id'] = $info->id;
        $data['username']= $info->username;
        $data['nickname'] = $info->nickname;
        $data['email'] = $info->email;
        //登录成功
        $this->ok($data);
    }
    public function logout(){
        //清空token  将需清空的token存入缓存，再次使用时，会读取缓存进行判断
        $token = \Token::getRequestToken();
        $delete_token = cache('delete_token') ?: [];
        $delete_token[] = $token;
        cache('delete_token', $delete_token, 86400);
        $this->ok();
    }


}